
var store_departamento;
var store_editor;

Ext.onReady(function()
{

    store_departamento = new X.store.Json({
        fields : [
            'codigoDepartamento',
            'nombreDepartamento'
        ]
    });

    store_editor = new X.store.Json({
        url    : '/resumencc/ajax-filtro',
        fields : [
            'codigo',
            'nombreRubro',
            'numeroComprobante',
            'fechaMovimiento',
            'concepto',
            'razonSocial',
            'monto'
        ]
    });

    store_editor.addListener('load', function(store, records, options){
        try{
            var sum = 0;
            for (var i=0; i< records.length; i++){
                sum += parseInt(records[i].get('monto'));
            }
            Ext.getCmp('total').setValue(sum);
        }
        catch(e){
            X.msg.FailureJs(e.message);
        }
    });

    var grid = new X.grid.GridPanel({
        id        : 'editor',
        height    : 220,
        width     : 600,
        store     : store_editor,
        useTbar   : false,
        useBbar   : false,

        columns:[
            new X.column.Text   ({header: 'Rubro',          width: 100,
                                  dataIndex:            'codigo'}),
            new X.column.Text ({header: 'Descripcion',    width: 150,
                                  dataIndex:       'nombreRubro'}),
            new X.column.Text   ({header: 'Comprobante N°', width: 100,
                                  dataIndex: 'numeroComprobante'}),
            new X.column.Date   ({header: 'Fecha',          width:  80,
                                  dataIndex:   'fechaMovimiento'}),
            new X.column.Text   ({header: 'Concepto',       width: 150,
                                  dataIndex:          'concepto'}),
            new X.column.Text   ({header: 'Proveedor',       width: 150,
                                  dataIndex:          'razonSocial'}),
            new X.column.Money  ({header: 'Monto',          width: 120,
                                  dataIndex:             'monto'})
            
        ]
    });

    new X.form.FormPanel2({
        title            : 'Generar resumen de egresos de caja chica',
        submitButtonText : 'Generar',
        returnButtonText : 'Cancelar',
        submitUrl        : '/resumencc/ajax-crear', //Generar el pdf
        returnUrl        : '/resumencc/pdf',      //Volver al menu inicial
        width            : 632,
        height           : 450,
        labelWidth       : 90,
        layout           : 'absolute',

        items:[
            new Ext.form.FieldSet({title:'Búsqueda de egresos', x: 10, y: 5, width: 600, height: 88,
                                   labelWidth: 110, layout:'absolute', items:
            [
                new X.field.Hidden({ id:'editorRows' }),
                { layout:'form', x: 5, y: 0 , items:[
                    new X.field.Combo ({
                        id           : 'filtroDepartamento',
                        hiddenName   : 'codigoDepartamento',
                        fieldLabel   : 'Centro de costos',
                        valueField   : 'codigoDepartamento',
                        displayField : 'nombreDepartamento',
                        width        : 305,
                        store        : store_departamento,
                        listeners    :{
                            select: function ( combo, record, index ) {
                                Ext.getCmp('nombre').setValue(record.get('nombreDepartamento'));
                            }
                        }
                    }),
                    new X.field.Hidden({ id:'nombre' })
                ]},{
                  layout:'form', x:5, y: 28, items: [
                    new X.field.Date ({fieldLabel:'Fecha Inicial', id:'filtroInicial', width:100,
                                       vtype: 'daterange', endDateField:'filtroFinal', allowBlank: true,
                                       listeners: {
                                           change: function(){ Ext.getCmp('listar').enable()},
                                           select: function(){ Ext.getCmp('listar').enable()}
                                       }
                    })
                ]},{
                  layout:'form', x:250, y: 28, labelWidth: 70, items: [
                    new X.field.Date ({fieldLabel:'Fecha Final',   id:'filtroFinal',   width:100,
                                       vtype: 'daterange', startDateField:'filtroInicial', maxValue: new Date(), allowBlank: true,
                                       listeners: {
                                           change: function(){ Ext.getCmp('listar').enable()},
                                           select: function(){ Ext.getCmp('listar').enable()}
                                       }
                    })
                ]},{ 
                  layout:'form', x: 475, y: 28, items:[
                    new Ext.Button ({text:'Listar', id: 'listar', width:100, 
                                     handler:cargar_grilla, disabled: true
                    })
                ]}
            ]}),
            new Ext.form.FieldSet({title:'Resultados', x: 10, y: 100,width: 600,items:[
                grid,
            ]}),
            {
                layout: 'form', x: 10, y:360, labelWidth:40, items:[
                    new X.field.Number({fieldLabel:'Total',  id:'total', width:150, readOnly: true}),
                ]
            }
        ]
    });

    // ajax para cargar los datos filtrador
    function cargar_grilla(){
        store_editor.setBaseParam('filtroDepartamento', Ext.getCmp('filtroDepartamento').getValue());
        store_editor.setBaseParam('filtroInicial',      Ext.getCmp('filtroInicial')     .getValue());
        store_editor.setBaseParam('filtroFinal',        Ext.getCmp('filtroFinal')       .getValue());
        store_editor.reload();
    }

    // validacion de filtroInicial y filtroFinal
    Ext.apply(Ext.form.VTypes, {
        daterangeText : 'Formato incorrecto',
        daterange     : function(val, field) {
            var date = field.parseDate(val);

            if(!date){
                return false;
            }
            if (field.startDateField) {
                var start = Ext.getCmp(field.startDateField);
                if (!start.maxValue || (date.getTime() != start.maxValue.getTime())) {
                    start.setMaxValue(date);
                    start.validate();
                }
            }
            else if (field.endDateField) {
                var end = Ext.getCmp(field.endDateField);
                if (!end.minValue || (date.getTime() != end.minValue.getTime())) {
                    end.setMinValue(date);
                    end.validate();
                }
            }
            return true;
        },
        totalText : 'Al menos un movimiento',
        total     : function(val, field) {
            return store_editor.getCount() > 0;
        }
    });
});
